/**
 * 象形符号等级专题图
 * 说明：表达意义同等级符号专题图，符号不再是圆，
 * 而是根据指标进行推荐响应的图形，如人口数用人
 * 展示，企业数用企业图表展示等
 */
import echarts from 'echarts'; // echarts 文件引入
import sgisLayerBase from '../../sfgis.layer.base';
import colorPicker from '../macrolayers/echarts.colorpicker'; // 颜色初始化配置文件
import styleModify from '../macrolayers/echarts.stylemodify.js';
import store from "../../../../pages/macro/store";
import { getMapLayers } from "vuex";

export default {
  layerNum: 0, // 麻点图多能叠加10个，过多时提示移除，防止太卡
  pictogramLayer: '',
  pictogramLayerInfo:{},
  image:"",
  maxValue:"",
  callback:"",
  map:"",
  colors: [
    "#EE7600",
    "#88E3CD",
    "#CD8C95",
    "#458B00",
    "#00EE76",
    "#A02395",
    "#00CDCD",
    "#00868B",
    "#CD5555",
    "#FF0000"
  ], // 麻点图配色方案
  /**
   * 创建专题图
   * @param {Object} map 地图实例
   * @param {Object} data 用于创建专题图的数据
   *      {
   *        "id": "", 专题图的id
   *        "name": "", 专题图的名称
   *        "datas": [
   *          {id:"",name:"",lon:"",lat:"",regioncode:"",regionname:""},{}
   *        ]
   *      }
   */

  createLayer(map, data,callback) {
    console.log(data)
    var compare = function(obj1, obj2) {
      var val1 = Number(obj1.value[2]);
      var val2 = Number(obj2.value[2]);
      if (val1 > val2) {
        return -1;
      } else if (val1 > val2) {
        return 1;
      } else {
        return 0;
      }
    };
    data.data = data.data.sort(compare);
    this.maxValue = Math.ceil((data.data[0].value[2]) / 50);
    if(map.overlayers["pictogram"] && map.overlayers["pictogram"] != "layer"){
      map.overlayers["pictogram"][0].remove();
    }
    this.callback = callback
    this.map = map;
    // 圆的大小 // 鼠标进入时的动态效果 // 颜色要动态改变 // 鼠标进入时的颜色
    let pictogramMarkers = this.createMarker(data.data, map);
    const pictogramLayer = pictogramMarkers;
    this.image = data.image;
    this.createCharts(pictogramMarkers, data.data, data.name, data.image);
    pictogramMarkers[0].chart.on("mousemove", function (params) {
      EventBus.$emit("table-actiontrigger", {
        regionCode: params.data.region
      });
      EventBus.$emit("onChart-action", { regionCode: params.data.region });
    });
    pictogramMarkers[0].chart.on("mouseout", function (params) {
      EventBus.$emit("table-heighLightOff", {
        regionCode: params.data.region
      });
      EventBus.$emit("offChart-action", { regionCode: params.data.region });
    });
    this.pictogramLayer = pictogramLayer;
    this.layerNum++;
    pictogramLayer.setVisible = this.setVisible; // 添加设置可见性函数
    pictogramLayer.setOpacity = this.setOpacity; // 添加设置图层透明度函数
    pictogramLayer.setZIndexOffset = this.setZIndexOffset; // 设置图层顺序函数
    pictogramLayer.autoCalgraph = this.autoCalgraph; // 添加计算图例函数
    this.pictogramLayerInfo.layerId = "pictogram";
    styleModify.onZoomScatter(map, pictogramLayer, this.pictogramLayerInfo.layerId); // 由于麻点图在放大平移时均会改变可见性，故有此函数
    pictogramLayer.layerId = this.pictogramLayerInfo.layerId;
    pictogramLayer.autoCalgraph = this.autoCalgraph;
    styleModify.layerOrder[this.pictogramLayerInfo.layerId] = styleModify.curZindex;
    styleModify.curZindex -= 1;

    this.pictogramLayerInfo.name = data.name;
    this.pictogramLayerInfo.type = 'pictogram';
    this.pictogramLayerInfo.show = data.showThumbnails !== false;
    


    store.commit("getMapLayers",this.pictogramLayerInfo)
    this.map.overlayers["pictogram"] = this.pictogramLayer
    this.map.overlayerInfos["pictogram"] = this.pictogramLayerInfo
    // sgisLayerBase.setOverLayers(this.pictogramLayerInfo);
    
    // 为当前layer绑定设置颜色的方法
    // pictogramLayer.setCustomColor = this.setCustomColor;
    return this.pictogramLayerInfo;
  },
  createMarker(datas, map) {
    const time = +new Date();
    const resultMarkers = [];
    let pictogramMaker = new EchartsLayer(map);
    pictogramMaker._container.className = "chart_fullscreen"
    pictogramMaker._container.id = "pictogram_chart_" + time;
    pictogramMaker._container.style['position'] = "fixed";
    resultMarkers.push(pictogramMaker);
    return resultMarkers;
  },
  createCharts(pictogramLayer, datas, name, image) {
    if(datas.length<=5){
      let i = 1;
      let optionTimer = setInterval(()=>{
        let dataValue = datas.slice(0,i)
        let option = {
          color: ["#1B9E77", "#D95F02", "#7570B3", "#E7298A", "#66A61E"],
          animation: false,
          tooltip: {
            formatter: function (params) {
              return `${params.name}:${params.value[2]}`;
            }
          },
          GLMap: {},
          series: [{
            name: name,
            type: 'scatter',
            coordinateSystem: 'GLMap',
            symbol: image?`image://${image}`:"",
            data: dataValue,
            symbolSize:  (val)=> {
              if (parseInt(val[2] / this.maxValue) >= 50) {
                return 50
              } else if (parseInt(val[2] / this.maxValue) <= 30) {
                return 30
              } else {
                return parseInt(val[2] / this.maxValue)
              }
            },
            label: {
              normal: {
                position: 'right',
                show: false
              },
              emphasis: {
                show: false
              }
            },
          }]
        };
        pictogramLayer[0].chart.setOption(option);
        i++;
        if(i > datas.length){
          this.pictogramLayerInfo.html = this.calgraph(this.pictogramLayer, this.pictogramLayerInfo.layerId,image);
          this.callback(this.pictogramLayerInfo)
          clearInterval(optionTimer)
        }
      },500)
    }else{
      let i = 5;
      let optionTimer = setInterval(()=>{
        let dataValue = datas.slice(0,i)
        let option = {
          color: ["#1B9E77", "#D95F02", "#7570B3", "#E7298A", "#66A61E"],
          animation: false,
          tooltip: {
            formatter: function (params) {
              return `${params.name}:${params.value[2]}`;
            }
          },
          GLMap: {},
          series: [{
            name: name,
            type: 'scatter',
            coordinateSystem: 'GLMap',
            symbol: image?`image://${image}`:"",
            data: dataValue,
            symbolSize:  (val)=> {
              if (parseInt(val[2] / this.maxValue) >= 50) {
                return 50
              } else if (parseInt(val[2] / this.maxValue) <= 30) {
                return 30
              } else {
                return parseInt(val[2] / this.maxValue)
              }
            },
            label: {
              normal: {
                position: 'right',
                show: false
              },
              emphasis: {
                show: false
              }
            },
          }]
        };
        pictogramLayer[0].chart.setOption(option);
        i+=5;
        if(i-datas.length > 5){
          this.pictogramLayerInfo.html = this.calgraph(this.pictogramLayer, this.pictogramLayerInfo.layerId,image);
          this.callback(this.pictogramLayerInfo)
          clearInterval(optionTimer)
        }
      },500)
    }

  },
  /**
   *
   * @param {Object} laryer
   * @param {String} colorParam
   */
  // setCustomColor(laryer, colorParam) {
  //   console.log(laryer, colorParam)
  //   const options = laryer[0].chart.getOption();
  // },
  /* *图层样式可见性设置函数 */
  setVisible(visible) {
    styleModify.setScatterVisible(visible, this.layerId, this[0]);
  },
  /* *设置图层透明度 */
  setOpacity(opacity) {
    this[0]._container.style.opacity = opacity;
  },
  /** 设置调整图层顺序函数*/
  setZIndexOffset(index) {
    styleModify.setZIndexOffset(index, this.layerId, this[0]);
  },
  /* *图例样式计算 */
  calgraph(pictogramLayer, layerId,image) {
    let mark_item = [];
    let layer_list = pictogramLayer[0].chart.getOption().series
    for (let i = 0; i < layer_list.length; i++) {
      let str = {
        name: layer_list[i].name,
        color: pictogramLayer[0].chart.getOption().color[i]
      }

      mark_item.push(str)
    }
    let html = `<div style="padding:6px" class="${layerId}">`;
    for (const key in mark_item) {
      html += `<div class='chart_item' style='display:flex;align-items: center;justify-content: flex-start;'>
      <div style='${image?"display:inline-block;width:10px;":"display:inline-block;width:10px;height:10px;border-radius:100%;background:#1B9E77"}'>
        <img style='width:100%' src='${image}'/>
      </div>
        <p>&nbsp;&nbsp;&nbsp;&nbsp;${mark_item[key].name}</p>
      </div>`;
    }
    html += '</div>';
    const layers = sgisLayerBase.overLayers;
    for (const key in layers) {
      if (layers[key].layerId === layerId) {
        layers[key].html = html;
      }
    }
    return html;
  },
  autoCalgraph(layerId, color) {
    const itemColor = color;
    const emphsisColor = 'red';
    const html = `
     <div class="${layerId}" style='text-align:center;padding:10px;'>
        <div style='display:inline-block;width:10px;height:10px;background:${itemColor};border-radius:10px' onmouseover="this.style.background='${emphsisColor}'" onmouseout="this.style.background='${itemColor}'"></div>
        <div style='display:inline-block;width:10px;height:10px;background:${itemColor};border-radius:10px;' onmouseover="this.style.background='${emphsisColor}'" onmouseout="this.style.background='${itemColor}'"></div>
        <div style='width:10px;height:10px;background:${itemColor};border-radius:10px' onmouseover="this.style.background='${emphsisColor}'" onmouseout="this.style.background='${itemColor}'"></div>
     </div>
    `;
    const layers = sgisLayerBase.overLayers;
    for (const key in layers) {
      if (layers[key].layerId === layerId) {
        layers[key].html = html;
      }
    }
  }
};
